<?php

namespace app\admin\controller\customform;

use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Data extends Backend
{

    /**
     * Data模型对象
     * @var \app\admin\model\customform\Data
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\customform\Data;

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total                                       = $this->model
                ->with(['user', 'customform'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['user', 'customform'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                $row->visible(['id', 'title', 'user_id', 'weigh', 'createtime', 'updatetime']);
                $row->visible(['user']);
                $row->getRelation('user')->visible(['username']);
                $row->visible(['customform']);
                $row->getRelation('customform')->visible(['title']);
            }
            $list   = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    //导出
    public function export()
    {
        $ids = $this->request->get('ids', '');

        $ids = json_decode($ids, true);

        if (!count($ids)) {
            $this->error('请选择导出数据');
        }

        $theme = $this->model->with('customform')->find($ids[0]);

        if (!$theme) {
            $this->error('主题不存在');
        }

        // 获取表单列表 并转为一维数组
        $config = json_decode($theme->customform->config, true);

        //$config = json_decode(file_get_contents($config_path), true);

        $dataconfig = $config['dataconfig'];

        //一维数组
        $config_list = array_merge([['id' => 1, 'config' => ['label' => 'ID']], ['id' => 2, 'config' => ['label' => '用户id']]], $this->get_one_array($dataconfig));

        //导出的数据列表
        $datalist = $this->model->all($ids);

        if ($datalist) {

            //导出列表
            $export_list = [];
            //json 转数组
            foreach ($datalist as $key => $value) {

                $data = json_decode($value['data'], true);

                // foreach ($config_list as $keys => $values) {
                //     if (isset($values['component'])) {
                //         $data[$keys] = $this->machining($config_list, $values);
                //     }
                // }

                $new_data = $this->machining($config_list, $data);

                $new_data[0]['config']['value'] = $value['id'];
                $new_data[1]['config']['value'] = $value['user_id'];
                $export_list[]                  = $new_data;
            }
        }

        $spreadsheet = new Spreadsheet();
        $sheet       = $spreadsheet->getActiveSheet()->setTitle('数据导出');

        //设置表头
        foreach ($config_list as $key => $value) {
            // 单元格内容写入
            $sheet->setCellValueByColumnAndRow($key + 1, 1, $value['config']['label']);
        }

        $row = 2; // 从第二行开始
        foreach ($export_list as $item) {
            $column = 1;
            foreach ($item as $value) {
                // 单元格内容写入
                $sheet->setCellValueByColumnAndRow($column, $row, is_array($value['config']['value']) ? json_encode($value['config']['value']) : $value['config']['value'] . " ");
                $column++;
            }
            $row++;
        }

        header('Content-Disposition: attachment;filename="' . time() . '.xlsx"');

        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        exit;
    }

    //递归成一维数组
    protected function get_one_array($array)
    {

        $list = [];
        foreach ($array as $key => $value) {
            if (isset($value['list'])) {
                $list = array_merge($list, $this->get_one_array($value['list']));
            } elseif ($this->fields($value['component'])) {

                $list[] = ['id' => isset($value['id']) ? (String) $value['id'] : '', 'config' => $value['config'], 'component' => $value['component']];
            }
        }
        return $list;
    }

    //排除字段
    protected function fields($str)
    {
        $list = ['cf-submit', 'cf-Divider', 'cf-html', 'cf-text', 'cf-Carousel'];

        $status = true;
        foreach ($list as $key => $value) {
            if ($value == $str) {
                $status = false;
            }
        }

        return $status;
    }

    //数据渲染
    protected function machining($config_list, $data)
    {
        foreach ($data as $keys => $values) {

            foreach ($config_list as $key => $value) {

                if ($value['id'] == $values['id']) {

                    $config_list[$key]['config']['value'] = $this->machining_value($value, $values['value']);
                }
            }

        }

        return $config_list;
    }

    //多选、单选、区域选择框、下拉选择框、开关
    protected function machining_value($config, $value)
    {
        switch ($config['component']) {
            //多选
            case 'cf-checkbox':
                $str = '';
                foreach ($config['config']['content'] as $k => $v) {
                    foreach ($value as $key => $vs) {
                        if ($v['key'] == $vs) {
                            $str .= $v['value'] . ",";
                        }
                    }
                }
                return $str;
                break;
            //单选
            case 'cf-radio':
                foreach ($config['config']['content'] as $k => $v) {
                    if ($v['key'] == $value) {
                        return $v['value'];
                    }
                }
                break;
            //下拉
            case 'cf-select':
                foreach ($config['config']['content'] as $k => $v) {
                    if ($v['key'] == $value) {
                        return $v['value'];
                    }
                }
                break;
            //区域
            case 'cf-Cascader':
                $region = json_decode(file_get_contents(ROOT_PATH . 'public/assets/addons/customform/region.json'), true);

                return $region[$value[0]]['label'] . "/" . $region[$value[0]]['children'][$value[1]]['label'] . "/" . $region[$value[0]]['children'][$value[1]]['children'][$value[2]]['label'];
                break;
            //图片上传
            case 'cf-upload-image':
                $str = '';
                foreach ($value as $key => $v) {
                    if (isset($v['url'])) {
                        $str .= cdnurl($v['url'], true) . ";";
                    }
                }
                return $str;
            //文件上传
            case 'cf-upload-file':
                $str = '';
                foreach ($value as $key => $v) {
                    if (isset($v['url'])) {
                        $str .= cdnurl($v['url'], true) . ";";
                    }
                }
                return $str;
            default:
                return $value;
                break;
        }
    }
}
